package com.lwj.mallchat.common.user.service.impl;

import cn.hutool.core.thread.NamedThreadFactory;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.lwj.mallchat.common.common.domain.vo.resp.ApiResult;
import com.lwj.mallchat.common.common.utils.JsonUtils;
import com.lwj.mallchat.common.user.dao.UserDao;
import com.lwj.mallchat.common.user.domain.entity.IpDetail;
import com.lwj.mallchat.common.user.domain.entity.IpInfo;
import com.lwj.mallchat.common.user.domain.entity.User;
import com.lwj.mallchat.common.user.service.IPService;
import io.github.classgraph.json.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.Destroyable;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author lwj
 * @ClassName IPServiceImpl
 * @date 2024/10/22 17:32
 */
@Service
@Slf4j
public class IPServiceImpl implements IPService, DisposableBean {

    @Autowired
    private UserDao userDao;

    private static ExecutorService executor = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(500), new NamedThreadFactory("refresh-ipDetail", false));

    @Override
    public void refreshIpDetailAsync(Long uid) {
        executor.execute(() -> {
            User user = userDao.getById(uid);
            IpInfo ipInfo = user.getIpInfo();
            if (Objects.isNull(ipInfo)) {
                return;
            }
            String ip = ipInfo.needRefreshIp();
            if (StringUtils.isBlank(ip)) {
                return;
            }
            IpDetail ipDetail = tryGetIpDetailOrNullTreeTimes(ip);
            if (Objects.nonNull(ipDetail)) {
                ipInfo.refreshIpDetail(ipDetail);
                User update = User.builder().id(uid).ipInfo(ipInfo).build();
//                update.setId(uid);
//                update.setIpInfo(ipInfo);
                userDao.updateById(update);
            }
        });
    }

    private static IpDetail tryGetIpDetailOrNullTreeTimes(String ip) {
        for (int i = 0; i < 3; i++) {
            IpDetail ipDetail = getIpDetailOrNull(ip);
            if (Objects.nonNull(ipDetail)) {
                return ipDetail;
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.error("tryGetIpDetailOrNullTreeTimes InterruptedException", e);
            }
        }
        return null;
    }

    private static IpDetail getIpDetailOrNull(String ip) {
        String data = HttpUtil.get("https://ip.taobao.com/outGetIpInfo?ip=" + ip + "&accessKey=alibaba-inc");
        ApiResult<IpDetail> result = JsonUtils.toObj(data, new TypeReference<ApiResult<IpDetail>>() {
        });
        IpDetail ipDetail = result.getData();
        return ipDetail;
    }


//    public static void main(String[] args) {
//        Date begin = new Date();
//        for (int i = 0; i < 100; i++) {
//            int nowi = i;
//            executor.execute(() -> {
////                IPServiceImpl ipService = new IPServiceImpl();
//                IpDetail detail = tryGetIpDetailOrNullTreeTimes("117.85.133.4");
//                if (Objects.nonNull(detail)) {
//                    Date date = new Date();
//                    System.out.println(String.format("第%d次成功，目前耗时%ds", nowi, date.getTime() - begin.getTime()));
//                }
//            });
//        }
//    }

    @Override
    public void destroy() throws Exception {
        executor.shutdown();
        if (!executor.awaitTermination(30, TimeUnit.SECONDS)) {//最多等30秒，处理不完就拉倒
            if (log.isErrorEnabled()) {
                log.error("Timed out while waiting for executor [{}] to terminate", executor);
            }
        }
    }
}